<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2023/11/13
 * Time: 10:42 AM
 */

namespace app\common\cachemodel\zl6;

use app\common\cachemodel\ZlcrTag;
use app\common\cachemodel\ZlUserVip;
use app\common\cachemodel\Goods;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\BaseCache;
use think\Log;
use XznsTools\cache\CacheManage;

class Zl6Meditation extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl6_meditation';

    protected $cacheModel = 'meditation.category';

    public function UpdateData(int $id, array $data)
    {
        try
        {
            $data['update_time'] = time();

            $this->where(['id' => $id])->update($data);
            // 更新缓存
            CacheManage::getInstance()->setCacheConfig($this->cacheModel,$id)->setCache($data);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 获取 冥想栏目列表
     * @param int $uid
     * @param int $type 1=>推荐  2=>专辑
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public function getPageDatas(int $uid, int $type, int $page, int $limit = 15)
    {
        $pageData = $this->pageDataIds($type, $page, $limit);

        $dataInfoList = $this->batchGetInfoByIds(array_keys($pageData['data']));

        $dataList = [];
        $nowTime = time();
        foreach ($pageData['data'] as $id => $s)
        {
            if (!isset($dataInfoList[$id]))
            {
                continue;
            }
            $item = $dataInfoList[$id];
            if ($item['end_time'] > 0 && ($item['end_time'] < $nowTime || $nowTime < $item['start_time'] - 604800))
            {   // 已过期 |  未开始 并且距离开始时间大于7天
                continue;
            }

            $dataList[] = $item;
        }
        if ($uid)
        {
            $vipLevel = (new ZlUserVip())->getUserVipLevel($uid);
            $isVip = $vipLevel > 0;
        } else
        {
            $isVip = false;
        }
        $pageData['data'] = $dataList ? $this->pageDataRese($dataList, $uid, $isVip, $type) : [];

        return $pageData;
    }

    /**
     * 获取 冥想栏目ID
     * @param int $type 1=>推荐  2=>专辑
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public function pageDataIds(int $type, int $page, int $limit)
    {
        $nowTime = time();
        $resData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $type)
            ->setPage($page)
            ->setPageSize($limit)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($type, $nowTime)
            {
                try
                {
                    $where = ['status' => 1];
                    if ($type === 2)
                    {
                        $where['category_type'] = ['>', 0];
                    }
                    $data = $this->where($where)->where(function ($quesy) use ($nowTime)
                    {
                        $quesy->where(['end_time' => 0])->whereOr(['end_time' => ['>', $nowTime]]);
                    })->order("sort {$sortType},id desc")->column('sort', 'id');

                    $resData = [];
                    foreach ($data as $id => $lastTime)
                    {
                        $resData[$id] = ['sort' => $lastTime];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'sort');

        return $resData;
    }

    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            return $this->where(['id' => ['in', $ids]])->column('status,sort,category_type,type,base_num,sub_num,title,description,desc,cate_tid,ability_tids,cover_img,share_img,lottie,guide_img,price,is_vip_free,start_time,end_time,remark,create_time,update_time', 'id');
        }
        catch (\Exception $e)
        {
            Log::write('Zl6Meditation model => ()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return [];
        }
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            if (isset($itemData['ability_tids']))
            {
                $itemData['ability_tids'] = array_map('intval', explode(',', $itemData['ability_tids']));
            }

            $data[$index] = arrayKeyData2int($itemData, ['id', 'status', 'sort', 'category_type', 'type', 'base_num', 'sub_num', 'start_time', 'end_time', 'cate_tid', 'is_vip_free', 'create_time']);
        }

        return $data;
    }

    /**
     * 分页数据重组
     * @param array $dataList
     * @param int $uid
     * @param bool $isVip 是否是VIP
     * @param int $type 1=>推荐  2=>专辑
     * @return array
     * @throws \Exception
     */
    public function pageDataRese(array $dataList, int $uid, bool $isVip, int $type)
    {
        $zlcrTagModel = new ZlcrTag();
        $zl6MeditationSubscribeModel = new Zl6MeditationSubscribe();
        $zl6MeditationUnlockDataModel = new Zl6MeditationUnlockData();
        $nowTime = time();
        // 水逆
        $list1 = [];
        // 新月
        $list2 = [];
        // 十二星座
        $list3 = [];
        $resDataList = [];
        foreach ($dataList as $itemData)
        {
            $tagIds = $itemData['ability_tids'];
            if ($itemData['cate_tid'])
            {
                $tagIds[] = $itemData['cate_tid'];
            }
            $tagListInfo = $zlcrTagModel->batchGetInfoByIds($tagIds);
            $tagList = [];
            if ($itemData['cate_tid'] && isset($tagListInfo[$itemData['cate_tid']]) && $tagListInfo[$itemData['cate_tid']])
            {
                $tagList[] = [
                    'name' => $tagListInfo[$itemData['cate_tid']]['tag_name'],
                    'bg_color' => $tagListInfo[$itemData['cate_tid']]['extend']['bg_color'] ?? '',
                    'color' => $tagListInfo[$itemData['cate_tid']]['extend']['txt_color'] ?? '',
                ];
            }
            foreach ($itemData['ability_tids'] as $tid)
            {
                if ($tid && isset($tagListInfo[$tid]) && $tagListInfo[$tid])
                {
                    $tagList[] = [
                        'name' => $tagListInfo[$tid]['tag_name'],
                        'bg_color' => $tagListInfo[$tid]['extend']['bg_color'] ?? '',
                        'color' => $tagListInfo[$tid]['extend']['txt_color'] ?? '',
                    ];
                }
            }
            $desList = $itemData['desc'] ? [$itemData['desc']] : [];
            $desList[] = $itemData['type'] === 1 ? '大众冥想' : '半定制冥想';
            $tipData = null;
            if (in_array($type, [1, 2], true) && $itemData['end_time'] > 0)
            {   // 推荐 ｜ 专辑
                if ($itemData['start_time'] > $nowTime)
                {   // 未开始
                    $tip = '时间：' . date('m月d日 H:i', $itemData['start_time']) . '至' . date('m月d日 H:i', $itemData['end_time']);
                    // 取当前 预约状态
                    if ($uid && $zl6MeditationSubscribeModel->isSubscribe($uid, $itemData['id']))
                    {   // 已预约
                        $subStatus = 3;
                    } else
                    {   // 获取当前 是否是 VIP ｜ 已购买  | 可预约状态 不是12星座类型
                        if ($isVip || $zl6MeditationUnlockDataModel->isUnlock($uid, $itemData['id'], 0))
                        {
                            $subStatus = 1;
                        } else
                        {
                            $subStatus = 2;
                        }
                    }
                } else
                {   // 进行中
                    $tip = date('m月d日 H:i', $itemData['end_time']) . ' 后结束，' . ($itemData['sub_num'] + $itemData['base_num']) . '人参与中...';
                    $subStatus = 4;
                }
                $tipData = [
                    'tip' => $tip,
                    'status' => $subStatus
                ];
            }
            $resData = [
                'id' => $itemData['id'],
                'img' => $itemData['cover_img'],
                'title' => $itemData['title'],
                'desc' => $desList,
                'tag_list' => $tagList,
                'tip_data' => $tipData,
                'style' => 1,
            ];
            if ($type === 2)
            {   // 专辑
                switch ($itemData['category_type'])
                {
                    case 1: // 十二星座
                        if (empty($list3))
                        {
                            $list3[] = ['id' => 0, 'img' => '/test/meditation/12astr.png', 'title' => '十二星座', 'desc' => ['准了针对十二星座的不同特征定制了不同的冥想课程，在这里你可以获得更适合你的冥想课程，帮助你调节自己的身心。'], 'tag_list' => [], 'tip_data' => null, 'style' => 2,];
                        }
                        $list3[] = $resData;
                        break;
                    case 2: // 新月
                        if (empty($list2))
                        {
                            $list2[] = ['id' => 0, 'img' => '/test/meditation/moon.png', 'title' => '新月', 'desc' => ['新月许愿是难得的机会，我们的潜意识便会浮现到表意识层面，因此我们就可以针对意识做出行动，最终增加了实现愿望的可能性。我们的冥想课程可以帮助你吸引更多的积极能量，实现自己的愿望。'], 'tag_list' => [], 'tip_data' => null, 'style' => 2,];
                        }
                        $list2[] = $resData;
                        break;
                    case 3: // 水逆
                        if (empty($list1))
                        {
                            $list1[] = ['id' => 0, 'img' => '/test/meditation/water.png', 'title' => '水逆', 'desc' => ['水逆（又称水星逆行）是一种天文现象，不同阶段有不同程度的影响。我们的冥想课程可以帮助你从调节身心的角度弱化水逆对你的负面影响。'], 'tag_list' => [], 'tip_data' => null, 'style' => 2,];
                        }
                        $list1[] = $resData;
                        break;
                }
            } else
            {
                $resDataList[] = $resData;
            }
        }

        if ($type === 2)
        {   // 专辑
            $resDataList = array_merge($list1, $list2, $list3);
        }
        return $resDataList;
    }

    /**
     * 获取商品信息
     * @param int $cid 课程栏目ID
     * @param $inSign
     * @return array
     * @throws ApiException
     * @throws \Exception
     */
    public function goodsInfo(int $cid, $inSign)
    {
        $goods = (new Goods())->GoodsTypeInfo(29);
        $gidTmp = current($goods)['id'];
        $meditationInfo = $this->getInfoById($cid);
        if (!$meditationInfo)
        {
            throw new ApiException('未知的课程');
        }
        if ($meditationInfo['category_type'] === 1)
        {
            if (!$inSign)
            {
                throw new ApiException('请选择星座');
            }
            $signName = (new Util())->signTypeName($inSign)['name'];
        }
        return [
            'id' => $gidTmp,
            'sort' => $meditationInfo['sort'],
            'status' => $meditationInfo['status'],
            'type' => 29,
            'name' => $meditationInfo['title'],
            'or_prize' => $meditationInfo['price'],
            'now_prize' => $meditationInfo['price'],
            'expire_time' => '',
            'extend' => isset($signName) ? '{"goods_des":"开通星座：' . $signName . '","ios_goods_des":"开通星座：' . $signName . '"}' : '',
        ];
    }
}
